<?php

namespace app\admin\controller;

use think\Request;
use app\admin\controller\Common;
use app\admin\model\Article as ArticleModel;
use app\admin\model\Cate as CateModel;
use app\admin\model\Messages as MessagesModel;
use think\Loader;
use app\admin\model\Special;

class Article extends Common
{

    public function edit(){
		//修改数据
		if (request()->isPost()) {
			$data = input('post.');
			$validate = Loader::validate('Article');
			if (!$validate->scene('edit')->check($data)) {
				$this->error($validate->getError());
			}
			$article = new ArticleModel();
			$save = $article->update($data);
			if ($save) {
				$this->success('修改文章成功','lst');
			}else{
				$this->error('修改文章失败');
			}
			return;
		}

		//显示从lst过来的数据
		$cate = new CateModel();
		$cateres = db('cate')->where(['typez' => 1])->select();
		$arts = db('article')->find(input('id'));
		$spec = Special::all();
		$this->assign(array(
			'cateres'=>$cateres,
			'arts'=>$arts,
            'spec' => $spec
		));
		return view();
	}

    public function add(){
        if (request()->isPost()) {
			$data = input('post.');
			$validate = Loader::validate('Article');
			if (!$validate->scene('add')->check($data)) {
				$this->error($validate->getError());
			}
			$article = new ArticleModel();
			$data['typez'] = 1;
			if ($article->save($data)) {
				$this->success('添加文章成功','lst');
			}else{
				$this->error('添加文章失败');
            }
		}
        $cate = new CateModel();
        $cateres = db('cate')->where('typez', 1)->select();
		// $cateres = $cate->getcate();
        $this->assign('cateres',$cateres);

        return view();
    }

    public function lst(){
        $artres = db('article')->alias('a')->where(['a.typez' => 1])->field('a.*,b.catename')->join('lan_cate b','a.cateid=b.id')->paginate(10);
        $this->assign('artres',$artres);
        return view();
    }

    public function del(){
		if (ArticleModel::destroy(input('id'))) {
			$this->success('删除文章成功','lst');
			# code...
		}else{
			$this->error('删除文章失败');
		}
	}

	public function messages(){
		// return '1';
		// die;
		$messages = new MessagesModel();
		// if(request()->isPost()){
			$id = input('id');
			$messagesres = $messages->get_messages($id);
			// return dump($messagesres);
			// die;
		// }
		$this->assign(array(
			'messagesres' => $messagesres
		));
		return view('messages/lst');
	}


}
